package com.xfunc.libncp;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.pm.PackageManager;
import android.graphics.Point;
import android.os.Build;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;

import java.lang.reflect.Field;
import java.util.UUID;

public class AppUtils {
    private static Application sApp;
    public static Application getApp() {
        if (sApp != null) return sApp;
        init(getApplicationByReflect());
        if (sApp == null) throw new NullPointerException("reflect failed.");
        return sApp;
    }
    public static void init( Application app) {
        if (app == null) {
            return;
        }
        if (sApp == null) {
            sApp = app;
            return;
        }
        sApp = app;
    }
    public static Activity getActivityFromView(View view) {
        if (null != view) {
            Context context = view.getContext();
            while (context instanceof ContextWrapper) {
                if (context instanceof Activity) {
                    return (Activity) context;
                }
                context = ((ContextWrapper) context).getBaseContext();
            }
        }
        return null;
    }
   static Application getApplicationByReflect() {
        try {
            @SuppressLint("PrivateApi") Class activityThreadClass = Class.forName("android.app.ActivityThread");
            Object thread = getActivityThread();
            if (thread == null) return null;
            Object app = activityThreadClass.getMethod("getApplication").invoke(thread);
            if (app == null) return null;
            return (Application) app;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    private static Object getActivityThread() {
        Object activityThread = getActivityThreadInActivityThreadStaticField();
        if (activityThread != null) return activityThread;
        return getActivityThreadInActivityThreadStaticMethod();
    }

    private static Object getActivityThreadInActivityThreadStaticField() {
        try {
            Class activityThreadClass = Class.forName("android.app.ActivityThread");
            Field sCurrentActivityThreadField = activityThreadClass.getDeclaredField("sCurrentActivityThread");
            sCurrentActivityThreadField.setAccessible(true);
            return sCurrentActivityThreadField.get(null);
        } catch (Exception e) {
            return null;
        }
    }

    private static Object getActivityThreadInActivityThreadStaticMethod() {
        try {
            Class activityThreadClass = Class.forName("android.app.ActivityThread");
            return activityThreadClass.getMethod("currentActivityThread").invoke(null);
        } catch (Exception e) {
            return null;
        }
    }
    public static String getPhoneInfo(){
        String text =  "\r\n";
        text += "获取设备手机制造商：" + Build.MANUFACTURER + "\r\n";
        text += "获取设备主板：" + Build.BOARD + "\r\n";
        text += "获取设CPU指令集：" + Build.SUPPORTED_ABIS.toString() + "\r\n";
        text += "获取设备AndroidID：" + DeviceInfo.getAndroidID() + "\r\n";
        text += "获取设备型号：" + DeviceInfo.getModel() + "\r\n";
        text += "获取唯一设备 ID：" + DeviceInfo.getUdid() + "\r\n";
        text += "获取设备 AppVersionCode：" + DeviceInfo.getVersionCode() + "\r\n";
        text += "获取唯一设备 AppVersionName：" + DeviceInfo.getVerName() + "\r\n";
        text += "获取设备系统版本号：" + Build.VERSION.RELEASE + "\r\n";
        text += "获取设备系统版本码：" + Build.VERSION.SDK_INT + "\r\n";
        text += "分辨率：" + DeviceInfo.getSystemScreenSize() + "\r\n";
        text += "屏幕尺寸：" + DeviceInfo.calcScreenSize() + "\r\n";
        text += "刷新率：" + DeviceInfo.getRefreshRate() + "\r\n";
        text += "屏幕dpi：" + getApp().getResources().getDisplayMetrics().densityDpi+ "\r\n";
        return text;
    }
    public static class DeviceInfo{
        public static double calcScreenSize() {
            DisplayMetrics metrics = new DisplayMetrics();
            WindowManager windowManager = (WindowManager) getApp().getSystemService(Context.WINDOW_SERVICE);
            windowManager.getDefaultDisplay().getMetrics(metrics);
            Point point = new Point();
            windowManager.getDefaultDisplay().getSize(point);
            double w = point.x / metrics.xdpi; // unit is inch
            double h = point.y / metrics.ydpi; // unit is inch
            double size = Math.sqrt(w * w + h * h);
            return size;
        }
        public static float getRefreshRate() {
            WindowManager windowManager = (WindowManager) getApp().getSystemService(Context.WINDOW_SERVICE);
            Display defaultDisplay = windowManager.getDefaultDisplay();
            return defaultDisplay.getRefreshRate();
        }
        public static String getSystemScreenSize(){
            DisplayMetrics dm=new DisplayMetrics();
            WindowManager windowManager = (WindowManager) getApp().getSystemService(Context.WINDOW_SERVICE);
            windowManager.getDefaultDisplay().getRealMetrics(dm);
            String result=dm.widthPixels+"*"+dm.heightPixels;
            return result;
        }
        public static String getAndroidID() {
            String id = Settings.Secure.getString(getApp().getContentResolver(), Settings.Secure.ANDROID_ID);
            return id == null ? "" : id;
        }
        public static String getModel() {
            String model = Build.MODEL;
            if (model != null) {
                model = model.trim().replaceAll("\\s*", "");
            } else {
                model = "";
            }
            return model;
        }
        public static String getUdid() {
            String androidID = getAndroidID();
            return "2" + UUID.nameUUIDFromBytes(androidID.getBytes()).toString().replace("-", "");
        }
        /**
         * 获取软件版本号
         */
        public static int getVersionCode() {
            int versionCode = 0;
            //获取软件版本号，对应AndroidManifest.xml下android：versionCode
            try {
                versionCode = getApp().getPackageManager().getPackageInfo(getApp().getPackageName(), 0).versionCode;
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
            return versionCode;
        }

        /**
         * 获取版本号名称
         */
        public static String getVerName() {
            String verName = "";
            try {
                verName = getApp().getPackageManager().getPackageInfo(getApp().getPackageName(), 0).versionName;
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
            return verName;
        }
    }
}
